package com.example.aicompositiongrader.model;

import android.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DeepSeekResponse {
    private static final String TAG = "DeepSeekResponse";
    private String id;
    private String object;
    private long created;
    private String model;
    private List<Choice> choices;
    private Usage usage;

    // 转换为我们应用内部的CompositionResponse格式
    public CompositionResponse toCompositionResponse() {
        CompositionResponse response = new CompositionResponse();

        // 初始化整体评价对象
        CompositionResponse.OverallEvaluation evaluation = new CompositionResponse.OverallEvaluation();
        // 初始化纠错列表
        List<CompositionResponse.Correction> corrections = new ArrayList<>();
        // 初始化优化建议列表
        List<String> optimizationSuggestions = new ArrayList<>();

        if (choices != null && !choices.isEmpty()) {
            Choice firstChoice = choices.get(0);
            if (firstChoice != null && firstChoice.getMessage() != null) {
                String content = firstChoice.getMessage().getContent();
                if (content == null) content = "";
                Log.d(TAG, "AI返回原始内容: " + content);

                // 1. 提取并设置学生原文
                String originalText = extractModuleContent(content, "【学生原文】", "【基础纠错】");
                response.setOriginalText(originalText);

                // 2. 提取并设置参考范文
                String referenceEssay = extractModuleContent(content, "【参考范文】", "");
                response.setReferenceEssay(referenceEssay);

                // 3. 设置整体评价内容
                String overallComment = extractModuleContent(content, "【整体评价】", "【改进方向】");
                evaluation.setComment(overallComment);
                // 解析星级评分
                parseScores(overallComment, evaluation);

                // 4. 解析内容并提取纠错信息
                corrections = parseCorrectionContent(content);

                // 5. 提取优化建议
                optimizationSuggestions = parseOptimizationSuggestions(content);

                // 6. 提取改进方向
                List<String> improvementDirections = parseImprovementDirections(content);
                response.setImprovementDirections(improvementDirections);

            } else {
                // 处理空消息的情况
                setDefaultValues(response, evaluation, corrections, optimizationSuggestions);
            }
        } else {
            // 处理空choices的情况
            setDefaultValues(response, evaluation, corrections, optimizationSuggestions);
        }

        // 将内部类对象设置到外部响应对象中
        response.setOverallEvaluation(evaluation);
        response.setCorrections(corrections);
        response.setOptimizationSuggestions(optimizationSuggestions);

        return response;
    }

    // 提取模块内容的通用方法，增强容错性
    private String extractModuleContent(String content, String startTag, String endTag) {
        // 尝试多种可能的标签格式，增强容错性
        String[] possibleStartTags = {
                startTag,
                startTag.trim(),
                startTag + "\n",
                "\n" + startTag
        };

        int startIndex = -1;
        for (String tag : possibleStartTags) {
            startIndex = content.indexOf(tag);
            if (startIndex != -1) {
                startIndex += tag.length();
                break;
            }
        }

        if (startIndex == -1) {
            Log.w(TAG, "未找到模块: " + startTag);
            return "【未找到" + startTag + "模块】";
        }

        int endIndex;
        if (endTag.isEmpty()) {
            endIndex = content.length();
        } else {
            // 尝试多种可能的结束标签格式
            String[] possibleEndTags = {
                    endTag,
                    endTag.trim(),
                    endTag + "\n",
                    "\n" + endTag
            };

            endIndex = content.length();
            for (String tag : possibleEndTags) {
                int tempIndex = content.indexOf(tag, startIndex);
                if (tempIndex != -1) {
                    endIndex = tempIndex;
                    break;
                }
            }
        }

        // 提取内容并处理空值
        String result = content.substring(startIndex, endIndex).trim();
        if (result.isEmpty()) {
            return startTag + "内容为空";
        }
        return result;
    }

    // 解析纠错内容，确保错误信息正确显示
    private List<CompositionResponse.Correction> parseCorrectionContent(String content) {
        List<CompositionResponse.Correction> corrections = new ArrayList<>();

        // 1. 先提取【基础纠错】整个模块的内容
        String correctionContent = extractModuleContent(content, "【基础纠错】", "【优化建议】");
        Log.d(TAG, "基础纠错原始内容: " + correctionContent);

        // 2. 检查是否存在明确的"无错误"标记，但即使有也保留原始信息
        boolean hasNoError = correctionContent.contains("错误类型：无") ||
                correctionContent.contains("未发现错误") ||
                correctionContent.contains("没有错误");

        // 3. 改进正则表达式，确保能匹配所有错误项
        Pattern pattern = Pattern.compile(
                "(\\d+\\.\\s*)?" +  // 匹配可能的序号（如"1. "）
                        "错误类型[:：]\\s*([^\\n]+?)\\s*" +  // 错误类型（非贪婪匹配）
                        "原文[:：]\\s*([^\\n]+?)\\s*" +      // 原文片段
                        "修改为[:：]\\s*([^\\n]+?)\\s*" +    // 修改建议
                        "(错误原因[:：]\\s*([^\\n]+?))?\\s*", // 错误原因（可选）
                Pattern.CASE_INSENSITIVE
        );

        Matcher matcher = pattern.matcher(correctionContent);
        int matchCount = 0;

        // 4. 循环匹配所有错误项
        while (matcher.find()) {
            matchCount++;
            CompositionResponse.Correction correction = new CompositionResponse.Correction();

            // 提取匹配到的分组
            String errorType = trimOrEmpty(matcher.group(2), "未知错误");
            String originalText = trimOrEmpty(matcher.group(3), "无原文");
            String correctedText = trimOrEmpty(matcher.group(4), "无修改建议");
            String reason = trimOrEmpty(matcher.group(6), "无原因说明");

            // 设置纠错信息
            correction.setErrorType(errorType);
            correction.setOriginalText(originalText);
            correction.setCorrectedText(correctedText);
            correction.setReason(reason);

            corrections.add(correction);
        }

        // 5. 如果没有匹配到任何错误，但内容不为空，显示原始内容供参考
        if (matchCount == 0) {
            Log.w(TAG, "未匹配到任何错误项，使用原始内容");

            // 如果明确表示无错误，添加友好提示
            if (hasNoError) {
                CompositionResponse.Correction correction = new CompositionResponse.Correction();
                correction.setErrorType("无错误");
                correction.setOriginalText("无");
                correction.setCorrectedText("未发现需要修改的内容");
                correction.setReason("文章内容符合规范，无需修改");
                corrections.add(correction);
            } else {
                // 否则显示解析失败但保留原始内容
                CompositionResponse.Correction correction = new CompositionResponse.Correction();
                correction.setErrorType("解析提示");
                correction.setOriginalText("格式可能不标准");
                correction.setCorrectedText("以下是原始纠错信息");
                correction.setReason(correctionContent);
                corrections.add(correction);
            }
        }

        return corrections;
    }

    // 解析优化建议
    private List<String> parseOptimizationSuggestions(String content) {
        List<String> suggestions = new ArrayList<>();
        String suggestionsContent = extractModuleContent(content, "【优化建议】", "【整体评价】");
        Log.d(TAG, "优化建议原始内容: " + suggestionsContent);

        if (suggestionsContent.contains("无优化建议") || suggestionsContent.isEmpty()) {
            suggestions.add("无优化建议");
            return suggestions;
        }

        // 按序号分割建议，增强容错性
        String[] items = suggestionsContent.split("\\n|\\d+\\.\\s*");
        for (String item : items) {
            item = item.trim();
            if (!item.isEmpty() && !item.equals("【优化建议】")) {
                suggestions.add(item);
            }
        }

        // 如果解析后为空，保留原始内容
        if (suggestions.isEmpty()) {
            suggestions.add("优化建议：" + suggestionsContent);
        }

        return suggestions;
    }

    // 新增：解析改进方向
    private List<String> parseImprovementDirections(String content) {
        List<String> directions = new ArrayList<>();
        String directionsContent = extractModuleContent(content, "【改进方向】", "【参考范文】");
        Log.d(TAG, "改进方向原始内容: " + directionsContent);

        if (directionsContent.contains("无改进方向") || directionsContent.isEmpty()) {
            directions.add("无明确改进方向");
            return directions;
        }

        // 按序号分割
        String[] items = directionsContent.split("\\n|\\d+\\.\\s*");
        for (String item : items) {
            item = item.trim();
            if (!item.isEmpty() && !item.equals("【改进方向】")) {
                directions.add(item);
            }
        }

        // 如果解析后为空，保留原始内容
        if (directions.isEmpty()) {
            directions.add("改进方向：" + directionsContent);
        }

        return directions;
    }

    // 解析整体评价中的星级评分
    private void parseScores(String overallComment, CompositionResponse.OverallEvaluation evaluation) {
        if (overallComment == null || overallComment.isEmpty() || overallComment.equals("无")) {
            return;
        }

        // 解析主题明确性评分
        evaluation.setThemeScore(parseScore(overallComment, "主题明确性"));
        // 解析结构完整性评分
        evaluation.setStructureScore(parseScore(overallComment, "结构完整性"));
        // 解析语言表达评分
        evaluation.setLanguageScore(parseScore(overallComment, "语言表达"));
        // 解析情感真实性评分
        evaluation.setEmotionScore(parseScore(overallComment, "情感真实性"));
    }

    // 解析单项评分
    private int parseScore(String content, String scoreName) {
        Pattern pattern = Pattern.compile(scoreName + "[:：]\\s*([★☆]+)\\s*\\(?(\\d+)星\\)?", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(content);

        if (matcher.find() && matcher.group(2) != null) {
            try {
                return Integer.parseInt(matcher.group(2).trim());
            } catch (NumberFormatException e) {
                Log.e(TAG, "解析评分失败", e);
                return 0;
            }
        }

        // 如果未找到明确评分，尝试从文本中提取
        Log.w(TAG, "未找到" + scoreName + "的明确评分");
        return 0;
    }

    // 添加默认纠错项，避免null值
    private void addDefaultCorrection(List<CompositionResponse.Correction> corrections) {
        CompositionResponse.Correction correction = new CompositionResponse.Correction();
        correction.setErrorType("无错误信息");
        correction.setOriginalText("无");
        correction.setCorrectedText("未获取到纠错内容");
        correction.setReason("系统未收到有效的纠错信息");
        corrections.add(correction);
    }

    // 设置默认值
    private void setDefaultValues(CompositionResponse response,
                                  CompositionResponse.OverallEvaluation evaluation,
                                  List<CompositionResponse.Correction> corrections,
                                  List<String> suggestions) {
        response.setOriginalText("未获取到学生原文");
        response.setReferenceEssay("未获取到参考范文");
        evaluation.setComment("未获取到有效批改内容");
        addDefaultCorrection(corrections);
        suggestions.add("未获取到优化建议");

        List<String> directions = new ArrayList<>();
        directions.add("未获取到改进方向");
        response.setImprovementDirections(directions);
    }

    // 处理空字符串的工具方法
    private String trimOrEmpty(String str, String defaultValue) {
        if (str == null || str.trim().isEmpty()) {
            return defaultValue;
        }
        return str.trim();
    }

    // 内部类定义
    public static class Choice {
        private int index;
        private Message message;
        private String finish_reason;

        public int getIndex() {
            return index;
        }

        public void setIndex(int index) {
            this.index = index;
        }

        public Message getMessage() {
            return message;
        }

        public void setMessage(Message message) {
            this.message = message;
        }

        public String getFinish_reason() {
            return finish_reason;
        }

        public void setFinish_reason(String finish_reason) {
            this.finish_reason = finish_reason;
        }
    }

    public static class Message {
        private String role;
        private String content;

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }

    public static class Usage {
        private int prompt_tokens;
        private int completion_tokens;
        private int total_tokens;

        public int getPrompt_tokens() {
            return prompt_tokens;
        }

        public void setPrompt_tokens(int prompt_tokens) {
            this.prompt_tokens = prompt_tokens;
        }

        public int getCompletion_tokens() {
            return completion_tokens;
        }

        public void setCompletion_tokens(int completion_tokens) {
            this.completion_tokens = completion_tokens;
        }

        public int getTotal_tokens() {
            return total_tokens;
        }

        public void setTotal_tokens(int total_tokens) {
            this.total_tokens = total_tokens;
        }
    }

    // Getters and Setters
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getObject() {
        return object;
    }

    public void setObject(String object) {
        this.object = object;
    }

    public long getCreated() {
        return created;
    }

    public void setCreated(long created) {
        this.created = created;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public List<Choice> getChoices() {
        return choices;
    }

    public void setChoices(List<Choice> choices) {
        this.choices = choices;
    }

    public Usage getUsage() {
        return usage;
    }

    public void setUsage(Usage usage) {
        this.usage = usage;
    }
}
